<?php

namespace App\Http\Controllers\Console;

use App\Http\Controllers\Controller;
use App\Model\LoginModel;
use App\Model\ShopModel;
use Flc\Dysms\Client;
use Flc\Dysms\Request\SendSms;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Service\RedisService;
use link1st\Easemob\App\Easemob;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class LoginController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * @param Request $request
     * @return false|string
     * 用户注册
     */
    public function register(Request $request){
        $phone = $request->post('username');
        $re = Verify_Phone($phone);
        if(!$re){
            return json_encode(['code'=>100,'msg'=>'请检查您输入的手机号',[]]);
        }
        $password = $request->post('password');
        $confirm_password = $request->post('confirm_password');
        if($password != $confirm_password){
            return json_encode(['code'=>100,'msg'=>'两次的密码输入不正确','data'=>[]]);
        }
        if(!$phone || !$password){
            return json_encode(['code'=>100,'msg'=>'用户名或密码不可缺失','data'=>[]]);
        }
        //验证码
        $phone_code = $request->post('code');
        if(!$phone_code){
            return json_encode(['code'=>100,'msg'=>'手机验证码不可为空','data'=>[]]);
        }

        $redis = app("redis.connection");
        $val = $redis->get($phone.'code');
        if(!$val){
            return json_encode(['data'=>'您的验证码已过期','code'=>100]);
        }
        if($val!==$phone_code){
            return json_encode(['data'=>'您输入的验证码错误','code'=>100]);
        }
        $re1 =  DB::table('shop')->where('username',$phone)->first();
        if($re1){
            return json_encode(['code'=>100,'msg'=>'此用户名已被注册，不可重复注册','data'=>[]]);
        }
        $data['username']=$phone;
        $data['password']=md5($password);
        $data['phone']=$phone;
        $data['type']=1;
        $data['create_at']=date('Y-m-d H:i:s');
       // $re2 = DB::table('shop')->insert($data);
        $re2 = DB::table('shop')->insertGetId($data);
        if($re2){
            //也往环信开放注册这个用户,环信密码固定为123456
                $user = new Easemob();
                $name = 'juchuyuncang'.$re2;
                $user = $user->publicRegistration($name,'123456');

            return json_encode(['code'=>200,'msg'=>'注册成功','data'=>['Imuser'=>$name,'Impass'=>'123456']]);
        }else{
            return json_encode(['code'=>100,'msg'=>'注册失败','data'=>[]]);
        }

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        /* $data = $this ->validate($request,[
             'username' => 'required',
             'password' => 'required',
         ]);*/
        $username = $request->post('username');
        $password = $request->post('password');
        $registration_id = $request->post('registration_id');
        if(!$username || !$password){
            return json_encode(['code'=>100,'msg'=>'用户名或密码不可缺失','data'=>[]]);
        }
        $shop = new ShopModel();
        //$re = $shop->where('username',$username)->first()->toArray();
        $re =  DB::table('shop')->where('username',$username)->first();

        if(!$re){
            return json_encode(['code'=>100,'msg'=>'用户名不存在','data'=>[]]);
        }
        if(md5($password)!=$re->password){
            return json_encode(['code'=>100,'msg'=>'密码输入错误','data'=>[]]);
        }
        //存储用户的Registration ID，用户登录成功的话更新入shop表中
        $result=DB::table('shop')->where('username',$username)->update(['registration_id'=>$registration_id]);

        $token = \Str::random (64);
        $redis = new RedisService();
        //登陆后存储用户的id、手机号、身份type值、极光推送身份registration_id
        $arr['uid']=$re->id;
        $arr['username']=$re->username;
        $arr['type']=$re->type;
        $arr['registration_id']=$registration_id;
        $arr = json_encode($arr);
        $data  = $redis->add($token,$arr);
        if($data['code'] != 200){
            return ['msg'=>'登录失败','code'=>1002];
       }
        return json_encode(['code'=>200,'msg'=>'登录成功','data'=>['token'=>$token]]);

    }
    /**
     * @param Request $request
     * @return false|string
     * 阿里云短信发送，发送其他类型短信只需要更改 $sendSms->setTemplateCode里面的短信模板id
     */
    public function send(Request $request)
    {
        //
        $phone = request()->post('phone');
        $re = Verify_Phone($phone);
        if(!$re){
            return json_encode(['code'=>100,'msg'=>'请检查您输入的手机号',[]]);
        }
        $config = [
            'accessKeyId'    => config('aliyunsms.accessKeyId'),
            'accessKeySecret' => config('aliyunsms.accessKeySecret'),
        ];
        $code = rand(100000, 999999);
        //手机验证码储存在redis中，过期时间5分钟
        $redis = app("redis.connection");
        $val = $redis->setex($phone.'code' , 300 , $code);

        // $val = $redis->get($phone.'code');

       // $val = $redis->get($phone.'code');


        if(!$val){
            return json_encode(['data'=>'redis储存失败','code'=>100]);
        }

        $client  = new Client($config);
        $sendSms = new SendSms;
        $sendSms->setPhoneNumbers($phone);
        $sendSms->setSignName(config('aliyunsms.sign_name'));
        $sendSms->setTemplateCode(config('aliyunsms.yanzhengma'));
        $sendSms->setTemplateParam(['code' => $code]);
        //发送的流水号，可选
        //$sendSms->setOutId('demo');
        $re = $client->execute($sendSms);
        //dump($re);
        if($re->Code==='OK'){
            //写入短信发送记录表
            $sms_log = [
                'type' => 0,
                'mobile' => $phone,
                'code' => $code,
                'checked' => 0,//还未验证
                'status' => 1,//已发送
                'ip' => getRealIp(),
                'created' => time(),
            ];
            $result = DB::table('sms_logs')->insert($sms_log);
            if($result){
                return json_encode(['code'=>200,'msg'=>'验证码发送成功','data'=>[]]);
            }else{
                return json_encode(['code'=>100,'msg'=>'验证码发送失败','data'=>[]]);
            }
        }

    }

    /**
     * @param Request $request
     * @return false|string
     * 用户忘记密码
     */
    public function findpass(Request $request){
        $phone = $request->post('phone');
        $phone_code = $request->post('phone_code');
        $password = $request->post('password');
        $confirm_password = $request->post('confirm_password');
        $re = Verify_Phone($phone);
        if(!$re){
            return json_encode(['code'=>100,'msg'=>'请检查您输入的手机号','data'=>[]]);
        }
        if(!$phone_code){
            return json_encode(['msg'=>'请输入验证码','code'=>100,'data'=>[]]);
        }
        $redis = app("redis.connection");
        $val = $redis->get($phone.'code');
        if(!$val){
            return json_encode(['msg'=>'您的验证码不存在或已过期','code'=>100,'data'=>[]]);
        }
        if($val!==$phone_code){
            return json_encode(['msg'=>'您输入的验证码错误','code'=>100,'data'=>[]]);
        }
        if(!$password || !$confirm_password){
            return json_encode(['code'=>100,'msg'=>'密码和确认密码不可为空','data'=>[]]);
        }
        if($password!=$confirm_password){
            return json_encode(['code'=>100,'msg'=>'您两次输入的密码不同','data'=>[]]);
        }
        $re = DB::table('shop')->where('phone',$phone)->update(['password'=>md5($password)]);
        if($re){
            return json_encode(['code'=>200,'msg'=>'恭喜！重置密码成功','data'=>[]]);
        }else{
            return json_encode(['code'=>100,'msg'=>'您新修改的密码与登录密码相同，无需修改！','data'=>[]]);
        }

    }


    public function qrcode(Request $request){
        //返回个人的邀请码
        $token = $request->header('Authorization');
        $redis = app("redis.connection");
        $val = $redis->get($token);
        if(!$val){
            return json_encode(['code'=>100,'msg'=>'token已过期，请从新登陆','data'=>[]]);
        }
        $val = json_decode($val,true);
        $val = json_decode($val,true);
        $shop_id=$val['uid'];

        $yaoqing_id='juchuyuncang'.$shop_id;
        $img = QrCode::size(183)->generate($yaoqing_id);
        //$img = QrCode::generate('This is QRcode create!');
        //dd($img);
        return json_encode(['code'=>200,'msg'=>'获取邀请码成功','data'=>['yaoqingma'=>$img]]);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Model\LoginModel  $loginModel
     * @return \Illuminate\Http\Response
     */
    public function show(LoginModel $loginModel)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Model\LoginModel  $loginModel
     * @return \Illuminate\Http\Response
     */
    public function edit(LoginModel $loginModel)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Model\LoginModel  $loginModel
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, LoginModel $loginModel)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Model\LoginModel  $loginModel
     * @return \Illuminate\Http\Response
     */
    public function destroy(LoginModel $loginModel)
    {
        //
    }
}
